<template>
    <el-form
        :inline="true"
        ref="searchFormRef"
        style="max-width: 100%;margin-top: 90px;margin-left: 50px"
        label-width="auto"
        :model="queryConditions"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="流程编码" prop="code">
            <el-input
                v-model="queryConditions.code"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-form-item label="流程名称" prop="name">
            <el-input
                v-model="queryConditions.name"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-form-item label="流程类型" prop="phoneNum">
            <el-input
                v-model="queryConditions.typeName"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" @click="resetForm">重置</el-button>
    </el-form>

    <WorkFlowPageUtil style="margin-top: 50px" :table-data="formattedTableData"
              :columns="tableColumns"
              :current-page="pageNo"
              :total="allPage"
              :page-size="pageSize"
              @page-change="handlePageChange"
              @action="handleTableAction"
              @edit="handleEditAction"
              @delete="handleDeleteAction"
                      @show="handleShowAction"
                      @deploy="handleDeployAction"
    />

    <!-- 弹窗显示 AddCustomer -->
    <el-dialog
        title="新增流程"
        v-model="showAddDialog"
        width="40%"
        :before-close="handleDialogClose"
    >
        <AddWorkFlowDialog
            @submit-success="handleAddSuccess"
            @cancel="handleDialogClose"
        />
    </el-dialog>
    <!-- 编辑客户弹窗 -->
    <el-dialog
        title="编辑流程"
        v-model="showEditDialog"
        width="40%"
        :before-close="handleDialogClose"
    >
<!--      :customer="editingCustomer" -->
        <AddWorkFlowDialog
            :workflow="editingWorkFlow"
            @submit-success="handleEditSuccess"
            @cancel="handleDialogClose"
        />
    </el-dialog>
</template>

<script setup lang="ts">
import TestPage from "@/test/TestPage.vue"
import AddCustomer from "@/basic-view/customer/AddCustomer.vue";
import {Search, RefreshRight} from '@element-plus/icons-vue'
import {ref, computed, reactive, nextTick} from 'vue';
import {ElMessageBox, ElMessage, type FormInstance, ElLoading} from 'element-plus'
import type {Customer} from '@/types/public-xs/Customer';
import axios from 'axios';
import AddWorkFlowDialog from "@/activiti/view/AddWorkFlowDialog.vue";
import type {WorkFlow} from "@/types/workflow/WorkFlow.ts";
import WorkFlowPageUtil from "@/activiti/view/WorkFlowPageUtil.vue";
import router from "@/router";
import request from "@/util/request.ts";

let pageNo = ref(1)
let pageSize = ref(5)
let allPage = ref(0)

//查询条件
const queryConditions = reactive({
    code: '',
    name: '',
  typeName: ''
})

const tableColumns = ref([
    {prop: 'index', label: '序号'},
    {prop: 'code', label: '流程编码'},
    {prop: 'name', label: '流程名'},
    {prop: 'typeName', label: '单据类型'},

])
let tableData = ref<Customer[]>([])
// 计算属性
const formattedTableData = computed(() => {
    return tableData.value.map((item, index) => ({
        ...item,
        index: (pageNo.value - 1) * pageSize.value + index + 1
    }));
});

const showAddDialog = ref(false); // 新增弹窗
const showEditDialog = ref(false); // 编辑弹窗
const editingWorkFlow = ref<WorkFlow | null>(null); // 当前编辑的工作流

const handlePageChange = (newPage: number) => {
    pageNo.value = newPage

    fetchData(newPage)
}


const handleTableAction = (actionName: string) => {
    console.log('触发操作:', actionName)
    // 处理具体业务逻辑
    if (actionName === 'add') {
        showAddDialog.value = true; // 打开新增弹窗
    }
}




//修改弹窗
const handleEditAction = (workflow: WorkFlow) => {
    editingWorkFlow.value = {...workflow}; // 复制客户数据
    showEditDialog.value = true; // 打开修改弹窗
};



const handleDeployAction = async (workflow: WorkFlow) => {

  let res = await request.post('workflowDesign/workFlow/deployWorkFlow', {
    url:workflow.url
  },{
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  });

  // const res = await axios({
  //   method: "post",
  //   url: 'http://localhost:9001/workFlow/deployWorkFlow',
  //   data: {
  //     url: workflow.url
  //   },
  //   headers: {
  //     'Content-Type': 'application/x-www-form-urlencoded',
  //   }
  // })

  if (res.data.data) {
    ElMessage.success("部署成功")
  } else {
    ElMessage.error("部署失败")
  }
};



const handleShowAction = async (workflow: WorkFlow) => {
  let res = await request.post('workflowDesign/workFlow/showWorkFlow', {
   url:workflow.url
  },{
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  });
  // const res = await axios({
  //   method: "post",
  //   url: 'http://localhost:9001/workFlow/showWorkFlow',
  //   data: {
  //     url: workflow.url
  //   },
  //   headers: {
  //     'Content-Type': 'application/x-www-form-urlencoded',
  //   }
  // })

  let xml = res.data.data

  await router.push({
    path: '/home/workflow/show', query: {
      xml: xml
    }
  })
};



const handleDeleteAction = async (customer: Customer) => {
    try {
        await ElMessageBox.confirm('确定删除此客户？此操作不可恢复。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await request.post(`basic/Customer/deleteCustomer?id=${customer.id}`,);
        ElMessage.success('删除成功');
        await fetchData(pageNo.value); // 刷新
    } catch (error) {
        ElMessage.error('删除失败，请稍后重试');
    }
};



const handleAddSuccess = () => {
    showAddDialog.value = false;
    fetchData(pageNo.value); // 刷新
};

const handleEditSuccess = () => {
    showEditDialog.value = false;
    // editingCustomer.value = null;
    fetchData(pageNo.value); // 刷新表格
};

const handleDialogClose = () => {
    ElMessageBox.confirm('确定关闭新增客户窗口？未保存的数据将丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        showAddDialog.value = false; // 确认关闭
        showEditDialog.value = false;
    })
};

const searchFormRef = ref<FormInstance>()

//查询
const search = () => {
    pageNo.value = 1; // 重置到第一页
    fetchData(1);
};

// 重置表单
const resetForm = () => {
    if (!searchFormRef.value) return;
    nextTick(() => {
        searchFormRef.value!.resetFields();
        pageNo.value = 1;
        fetchData(1);
    });
};

async function fetchData(pageNo: number) {
    try {
      //http://localhost:9001
        let response = await request.post('workflowDesign/workFlow/getWorkFlowList', {
            pageNo: pageNo,
            pageSize: pageSize.value,
            code: queryConditions.code,
            name: queryConditions.name,
        });
        tableData.value = response.data.data.list;
        allPage.value = response.data.data.total;
        console.log(tableData.value)
    } catch (error) {
        ElMessage.error('获取流程数据失败');
        tableData.value = [];
        allPage.value = 0;
    }
}


fetchData(1)
</script>


<style scoped>

</style>
